package org.grow.auth.config;

import org.grow.auth.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.web.filter.CharacterEncodingFilter;

/**
 * @Author: xwg
 * @CreateDate: 2021/10/13
 */
@EnableRedisHttpSession
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DefaultAuthSuccessHandler defaultAuthSuccessHandler;
    @Autowired
    private DefaultAuthFailureHandler defaultAuthFailureHandler;

    @Autowired
    private DefaultLogoutSuccessHandler defaultLogoutSuccessHandler;
    @Autowired
    private AnonymousProvider anonymousProvider;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().disable();
        http.csrf().disable();
        http.httpBasic().disable();
//        登录四步走
//        登录第一步 绑定数据
        http.formLogin()
                .loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
//                登录第四步 登录 成功/失败
                .successHandler(defaultAuthSuccessHandler)
                .failureHandler(defaultAuthFailureHandler);
        http.logout()
                .deleteCookies("JSESSIONID","SESSIONID","SESSION")
                .invalidateHttpSession(true)
                .logoutSuccessHandler(defaultLogoutSuccessHandler);
        http.anonymous()
                .principal(anonymousProvider.provide());
    }

    @Autowired
    private UserInfoService userInfoService;
//    登录第二步
    @Override
    protected UserDetailsService userDetailsService() {
        return userInfoService;
    }
//    登录第三步 比较
    @Bean
    public PasswordEncoder passwordEncoder(){
//        return new BCryptPasswordEncoder();
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return charSequence.toString().equals(s);
            }
        };
    }
}
